package service;

import com.thoughtworks.xstream.XStream;
import entity.BaseMessage;
import entity.TextMessage;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import test.TestAccess;

import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.logging.Logger;


import static test.TuLingApiUtil.getReqMes;


/**
 * @ClassName WxService
 * @Author wuyuyang
 * @Date 2022/1/12 16:49
 * @Description WxService
 * @Version 1.0
 */
public class WxService {
    private static final String TOKEN = "abc";
    /**
     * 验证签名
     * @param timestamp
     * @param nonce
     * @param signature
     * @return
     */
    public static boolean check(String timestamp, String nonce, String signature) {
        // 1）将token、timestamp、nonce三个参数进行字典序排序
        String[] strs = new String[] { TOKEN, timestamp, nonce };
        Arrays.sort(strs);
        // 2）将三个参数字符串拼接成一个字符串进行sha1加密
        String str = strs[0] + strs[1] + strs[2];
        String mysig = sha1(str);
        // 3）开发者获得加密后的字符串可与signature对比，标识该请求来源于微信
        return mysig.equalsIgnoreCase(signature); // 进行字符串比对
    }

    /**
     * 进行sha1加密
     *
     * @param
     * @return
     */
    private static String sha1(String src) {
        try {
            // 获取一个加密对象
            MessageDigest md = MessageDigest.getInstance("sha1"); // 获取加密对象
            // 加密
            byte[] digest = md.digest(src.getBytes());
            char[] chars = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' };
            StringBuilder sb = new StringBuilder();
            // 处理加密结果
            for (byte b : digest) {
                sb.append(chars[(b >> 4) & 15]);
                sb.append(chars[b & 15]);
            }
            return sb.toString();
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 将接受到的消息转化成map
     * @param
     * @return
     */
    public static Map<String, String> parseRequest(InputStream is) {
        Map<String,String> map = new HashMap<String,String>();
        //1.通过io流得到文档对象
        SAXReader saxReader = new SAXReader();
        Document document = null;
        try {
            document = saxReader.read(is);
        } catch (DocumentException e) {
            e.printStackTrace();
        }
        //2.通过文档对象得到根节点对象
        Element root = document.getRootElement();
        //3.通过根节点对象获取所有子节点对象
        List<Element> elements = root.elements();
        //4.将所有节点放入map
        for (Element element : elements) {
            map.put(element.getName(), element.getStringValue());
        }
        return map;
    }


    /**
     * 事件消息回复
     */
    public static String getRespose(Map<String, String> requestMap) throws UnsupportedEncodingException {
        BaseMessage msg = null;
        // 根据用户发送消息的类型,做不同的处理
        String msgType = requestMap.get("MsgType");
        switch (msgType) {
            case "text":
                msg = dealTextMsg(requestMap);
                break;
            case "news":
                break;
            default:
                break;
        }
        // System.out.println(msg);
        // 将处理结果转化成xml的字符串返回
        if (null != msg) {
            return beanToXml(msg);
        }
        return null;
    }


    /**
     * 将回复的消息类转成xml字符串
     *
     * @param msg
     * @return
     */
    public static String beanToXml(BaseMessage msg) {
        XStream stream = new XStream();
        stream.processAnnotations(TextMessage.class);
//      stream.processAnnotations(NewsMsg.class);
        String xml = stream.toXML(msg);
        return xml;
    }


    /**
     * 当用户发送是文本消息的处理逻辑
     *
     * @param
     * @return
     */
    private static BaseMessage dealTextMsg(Map<String, String> requestMap) throws UnsupportedEncodingException {
        //用户发来的内容
        String msg = requestMap.get("Content");
        System.out.println(msg);
        //调用方法返回聊天的内容
        TestAccess ta = new TestAccess();
        String resp = ta.getAnswer(msg);
        System.out.println("回复是>>>>"+resp);
        TextMessage tm = new TextMessage(requestMap,resp);
        return tm;
    }


}
